//
//  MovableObject.m
//  Soccer
//
//  Created by Hyun-Woong Kim on 09. 04. 29.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MovableObject.h"
#import "ClientManager.h"

@implementation MovableObject

@synthesize prevPosition;
@synthesize position;
@synthesize dirRad;
@synthesize speed;
@synthesize isMoving;

- (id)init
{
	return [self initWithPosition:CGPointMake(0, 0) dirRad:0. speed: 10];
}

- (id)initWithPosition:(CGPoint)pos
{
	return [self initWithPosition:pos dirRad:0. speed:10];
}

- (id)initWithPosition:(CGPoint)pos dirRad:(double)rad speed:(int)sp
{
	if (self = [super init])
	{
		position = prevPosition = pos;
		dirRad = rad;
		speed = sp;
		isMoving = NO;
	}
	return self;
}

- (void)dealloc
{
	[super dealloc];
}

- (void)moveToNextPosition
{
	if (!self.isMoving)
		return;
	
	CGFloat newX = position.x;
	CGFloat newY = position.y;

	newX += speed * cos(dirRad);
	newY += speed * sin(dirRad);
	
	prevPosition = position; // 골잡기 판정에 사용하기 위해 이전 위치 저장
	position = [self checkOutline:CGPointMake(newX, newY)]; // check outline
}

- (CGPoint)checkOutline:(CGPoint)pos
{
	return [[ClientManager sharedManager].match checkOutline:pos];
}

- (void)spriteNeedsUpdates:(ObjectSprite *)sprite
{
	[self moveToNextPosition];
	
	[sprite setZOrder:1000 - position.y];
	sprite.position = CGPointMake(position.x, position.y + sprite.transformAnchor.y);
}

- (double)getDistanceFrom:(CGPoint)point1 To:(CGPoint)point2
{
	float xDiff = point1.x - point2.x;
	float yDiff = point1.y - point2.y;
	double distance = sqrt(xDiff*xDiff + yDiff*yDiff);
	
	return distance;
}

@end
